package com.yz.food.controller;

import com.yz.food.common.Const;
import com.yz.food.common.ServerResponse;
import com.yz.food.pojo.Category;
import com.yz.food.pojo.User;
import com.yz.food.service.CategoryService;
import com.yz.food.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 跳转到登录或者注册界面
     */
    @RequestMapping("page/loginOrRegister")
    public String loginOrRegisterPage(ModelMap modelMap) {

        List<Category> categories = categoryService.getAll();
        modelMap.addAttribute("categories", categories);
        return "loginOrRegister";
    }

    /**
     * 注册功能
     */
    @RequestMapping("user/register")
    @ResponseBody
    public ServerResponse userRegister(User user) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("注册失败！");
        }
        int count = userService.getByEmail(user.getEmail());
        if (count > 0) {
            return ServerResponse.createByErrorMessage("该邮箱已经被占用！");
        }
        int result = userService.register(user);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("注册成功，请前去登录！");
        }
        return ServerResponse.createByErrorMessage("注册失败！");
    }

    /**
     * 用户登录
     */
    @RequestMapping("user/login")
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        String backUrl = request.getHeader("Referer");
        User u = userService.getUserByEmail(user);
        if (u == null) {
            return ServerResponse.createByErrorMessage("账户名或密码错误");
        }
        request.getSession(true).setAttribute(Const.CURRENT_USER,u);
        return ServerResponse.createBySuccess("登录成功", backUrl);
    }
}
